<template>
  <div class="volunteer-page">
    <h1 class="page-title">志愿者管理中心</h1>

    <div class="container">
      <!-- 中间内容展示区域 -->
      <div class="content-area">
        <!-- 申请表单视图 -->
        <div v-if="showApplyForm" class="apply-form-view">
          <ApplyForm
            @application-submitted="handleApplicationSubmitted"
            @cancel="showApplyForm = false"
          />
        </div>

        <!-- 志愿者申请状态查询视图 -->
        <div v-else class="status-view">
          <div class="status-header">
            <h2>志愿者申请状态查询</h2>
            <p class="status-subtitle">在这里可以查看您的志愿者申请状态和审核进度</p>

            <!-- 添加申请按钮 -->
            <button
              v-if="canApply"
              @click="showApplyForm = true"
              class="btn-apply-main"
            >
              {{ getApplyButtonText() }}
            </button>
          </div>

          <!-- 加载状态 -->
          <div v-if="loading" class="loading-state">
            <div class="spinner"></div>
            <p>加载中...</p>
          </div>

          <!-- 错误状态 -->
          <div v-else-if="error" class="error-state">
            <div class="error-icon">⚠️</div>
            <p>{{ error }}</p>
            <button @click="loadApplication" class="retry-btn">重试</button>
          </div>

          <!-- 没有申请的情况 -->
          <div v-else-if="!existingApplication" class="no-application">
            <div class="empty-icon">📝</div>
            <h3>您还没有提交志愿者申请</h3>
            <p class="empty-hint">点击上方按钮开始您的志愿者申请</p>
          </div>

          <!-- 有申请的情况 -->
          <div v-else class="application-details">
            <div class="application-card">
              <div class="card-header">
                <h3>申请详情</h3>
                <span :class="`status-badge status-${existingApplication.status}`">
                  {{ getStatusText(existingApplication.status) }}
                </span>
              </div>

              <div class="application-info">
                <div class="info-grid">
                  <div class="info-item">
                    <label>姓名：</label>
                    <span>{{ existingApplication.name }}</span>
                  </div>
                  <div class="info-item">
                    <label>电话：</label>
                    <span>{{ existingApplication.phone }}</span>
                  </div>
                  <div class="info-item">
                    <label>邮箱：</label>
                    <span>{{ existingApplication.email }}</span>
                  </div>
                  <div class="info-item">
                    <label>部门：</label>
                    <span>{{ existingApplication.department }}</span>
                  </div>
                  <div class="info-item">
                    <label>职位：</label>
                    <span>{{ existingApplication.position }}</span>
                  </div>
                  <div class="info-item">
                    <label>申请时间：</label>
                    <span>{{ formatDate(existingApplication.applyTime) }}</span>
                  </div>
                </div>

                <div class="detail-section">
                  <label>相关经历：</label>
                  <p>{{ existingApplication.experience || '无' }}</p>
                </div>

                <div v-if="existingApplication.reviewNotes" class="detail-section">
                  <label>审核备注：</label>
                  <p class="review-notes">{{ existingApplication.reviewNotes }}</p>
                </div>
              </div>

              <!-- 取消申请按钮 -->
              <div v-if="existingApplication.status === 'pending'" class="action-buttons">
                <button
                  @click="cancelApplication"
                  class="btn-cancel-application"
                  :disabled="isCancelling"
                >
                  {{ isCancelling ? '取消中...' : '取消申请' }}
                </button>
              </div>

              <!-- 重新申请按钮 -->
              <div v-if="existingApplication.status === 'rejected'" class="action-buttons">
                <button
                  @click="showApplyForm = true"
                  class="btn-reapply-main"
                >
                  重新申请
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import ApplyForm from "./ApplyForm.vue";
import { request } from '@/utils/request';

// 志愿者申请类型
interface VolunteerApplication {
  volunteerID?: number;
  userID: number;
  name: string;
  phone: string;
  email: string;
  department: string;
  position: string;
  experience: string;
  status: string;
  applyTime: string;
  reviewNotes?: string;
}

// API 响应类型
interface VolunteerApiResponse {
  success: boolean;
  message?: string;
  application?: VolunteerApplication;
}

// 状态管理
const loading = ref(false);
const error = ref('');
const existingApplication = ref<VolunteerApplication | null>(null);
const showApplyForm = ref(false);
const isCancelling = ref(false);

// 计算属性：是否可以申请
const canApply = computed(() => {
  if (!existingApplication.value) return true; // 没有申请记录，可以申请
  if (existingApplication.value.status === 'rejected') return true; // 被拒绝可以重新申请
  return false; // 待审核或已通过都不能申请
});

// 获取申请按钮文本
const getApplyButtonText = () => {
  if (!existingApplication.value) return '立即申请';
  if (existingApplication.value.status === 'rejected') return '重新申请';
  return '立即申请';
};

// 加载申请信息
const loadApplication = async (): Promise<void> => {
  try {
    loading.value = true;
    error.value = '';

    console.log('正在加载志愿者申请信息...');
    const response: VolunteerApiResponse = await request.get('/api/volunteer/my-application');
    console.log('志愿者申请响应:', response);

    if (response.success) {
      existingApplication.value = response.application || null;
      if (!existingApplication.value) {
        console.log('用户还没有志愿者申请');
      } else {
        console.log('已存在的申请:', existingApplication.value);
      }
    } else {
      error.value = response.message || '获取申请信息失败';
      existingApplication.value = null;
    }
  } catch (err: unknown) {
    console.error('加载申请信息失败:', err);
    error.value = '网络错误，无法获取申请信息';
    existingApplication.value = null;
  } finally {
    loading.value = false;
  }
};

// 取消申请
const cancelApplication = async (): Promise<void> => {
  if (!confirm('确定要取消志愿者申请吗？取消后将无法恢复。')) {
    return;
  }

  isCancelling.value = true;

  try {
    console.log('取消志愿者申请...');
    const response: VolunteerApiResponse = await request.delete('/api/volunteer/cancel');
    console.log('取消响应:', response);

    if (response.success) {
      alert('申请已取消');
      await loadApplication(); // 重新加载数据
    } else {
      alert(`取消失败：${response.message}`);
    }
  } catch (err: unknown) {
    console.error('取消申请失败:', err);
    alert('取消失败，请稍后重试');
  } finally {
    isCancelling.value = false;
  }
};

// 处理申请提交成功
const handleApplicationSubmitted = (): void => {
  showApplyForm.value = false;
  loadApplication(); // 重新加载申请状态
};

// 格式化日期
const formatDate = (dateString: string): string => {
  if (!dateString) return '暂无数据';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 获取状态文本
const getStatusText = (status: string): string => {
  switch (status) {
    case 'pending':
      return '审核中';
    case 'approved':
      return '已通过';
    case 'rejected':
      return '未通过';
    default:
      return status;
  }
};

// 初始化加载
onMounted(() => {
  loadApplication();
});
</script>

<style scoped>
/* 添加主申请按钮样式 */
.btn-apply-main {
  padding: 12px 24px;
  background: linear-gradient(135deg, #31B310, #2a990e);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  margin-top: 15px;
}

.btn-apply-main:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

.btn-reapply-main {
  padding: 12px 24px;
  background: linear-gradient(135deg, #1890ff, #096dd9);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  margin-top: 15px;
}

.btn-reapply-main:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

/* 确保申请表单视图占满整个区域 */
.apply-form-view {
  width: 100%;
  height: 100%;
}

.volunteer-page {
  width: 100%;
  height: 100%;
}

.page-title {
  text-align: center;
  font-size: 2.5rem;
  font-weight: bold;
  margin: 0 0;
  color: #31B310;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
  background: linear-gradient(to right, #31B310, #3498db);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.container {
  display: flex;
  justify-content: center;
  align-items: stretch;
  height: calc(100vh - 150px);
  gap: 30px;
  padding: 20px;
  box-sizing: border-box;
}

.content-area {
  width: 100%;
  max-width: 1000px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf5 100%);
  border-radius: 15px;
  padding: 30px;
  box-sizing: border-box;
  display: flex;
  align-items: flex-start;
  justify-content: flex-start;
  min-height: 500px;
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
  overflow-y: auto;
}

.status-view {
  width: 100%;
}

.status-header {
  text-align: center;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 2px solid #e9ecef;
}

.status-header h2 {
  color: #2c3e50;
  font-size: 2rem;
  margin: 0 0 10px 0;
  background: linear-gradient(to right, #31B310, #3498db);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.status-subtitle {
  color: #666;
  font-size: 1.1rem;
  margin: 0;
}

/* 加载状态 */
.loading-state {
  text-align: center;
  padding: 60px 0;
}

.spinner {
  width: 60px;
  height: 60px;
  margin: 0 auto 20px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #31B310;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-state p {
  color: #666;
  font-size: 16px;
  margin: 0;
}

/* 错误状态 */
.error-state {
  text-align: center;
  padding: 60px 0;
  color: #dc3545;
}

.error-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.error-state p {
  margin-bottom: 20px;
  font-size: 16px;
}

.retry-btn {
  padding: 10px 24px;
  background: linear-gradient(135deg, #31B310, #2a990e);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.retry-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

/* 没有申请的情况 */
.no-application {
  text-align: center;
  padding: 80px 0;
  color: #6c757d;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.no-application h3 {
  color: #2c3e50;
  margin-bottom: 10px;
  font-size: 1.5rem;
}

.empty-hint {
  margin-bottom: 30px;
  font-size: 1rem;
  opacity: 0.7;
}

/* 申请详情卡片 */
.application-card {
  background: white;
  border-radius: 15px;
  padding: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border: 2px solid #e9ecef;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 20px;
  border-bottom: 2px solid #f0f2f5;
}

.card-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.5rem;
  font-weight: 600;
}

.status-badge {
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.status-pending {
  background: linear-gradient(135deg, #fffbe6, #fff1b8);
  color: #faad14;
  border: 1px solid #ffe58f;
}

.status-approved {
  background: linear-gradient(135deg, #f6ffed, #d9f7be);
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-rejected {
  background: linear-gradient(135deg, #fff2f0, #ffccc7);
  color: #ff4d4f;
  border: 1px solid #ffa39e;
}

/* 申请信息 */
.application-info {
  margin-bottom: 25px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
  margin-bottom: 25px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 0;
  border-bottom: 1px solid #f0f2f5;
}

.info-item label {
  color: #6c757d;
  font-weight: 500;
  min-width: 80px;
}

.info-item span {
  color: #495057;
  font-weight: 500;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section label {
  display: block;
  color: #6c757d;
  font-weight: 500;
  margin-bottom: 8px;
  font-size: 14px;
}

.detail-section p {
  color: #495057;
  line-height: 1.6;
  margin: 0;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #31B310;
}

.review-notes {
  background: #fff2f0 !important;
  border-left: 4px solid #ff4d4f !important;
  color: #d9363e !important;
}

/* 操作按钮 */
.action-buttons {
  text-align: center;
  padding-top: 20px;
  border-top: 1px solid #f0f2f5;
}

.btn-cancel-application {
  padding: 10px 24px;
  background: linear-gradient(135deg, #ff4d4f, #d9363e);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.btn-cancel-application:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

.btn-cancel-application:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

/* 申请表单视图 */
.apply-form-view {
  width: 100%;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .container {
    padding: 15px;
  }

  .content-area {
    padding: 20px;
  }

  .card-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }

  .application-card {
    padding: 20px;
  }

  .status-header h2 {
    font-size: 1.5rem;
  }
}
</style>
